<?php


namespace app\api\logic;


use app\api\model\Label as LabelModel;
use app\api\model\Posts as PostsModel;
use app\api\model\PostLike as PostLikeModel;
use app\api\model\Airport as AirportModel;
use app\api\model\Area as AreaModel;
use app\api\model\Merchant as MerchantModel;
use think\facade\Session;

class Posts
{
    private $merchantID;
    private $postsModel;
    private $postsLikeModel;
    private $airportModel;

    public function __construct(PostsModel $postsModel,AirportModel $airportModel,PostLikeModel $postsLikeModel)
    {
        $this->merchantID=Session::get('userId');
        $this->postsModel=$postsModel;
        $this->postsLikeModel=$postsLikeModel;
        $this->airportModel=$airportModel;
    }

    public function index(){
        return $this->merchantModel->info($this->merchantID);
    }

    public function info($id){
        $info=$this->postsModel->info($id);
        if(empty($info)) return false;
        if($this->merchantID){
            $info['is_like']=PostLikeModel::where(['mid'=>$this->merchantID,'type'=>Session::get('userType'),'post_id'=>$id])->count();
        }else{
            $info['is_like']=0;
        }
        $info['share_url']=$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/index.html#/details?id='.$id;
        return $info;
    }

    public function add($data){
        $req['code']=0;
        if(Session::get('userType')!=config('data.role_type.merchant')){
            $req['msg']='Insufficient permissions for the current user';
            return $req;
        }

        $data['merchant_id']=$this->merchantID;
//        $data['label']=isset($data['label'])?json_encode(explode(',',$data['label'])):'[]';

//        $files=request()->file('source');

        //判断商户是否被锁定
        $count= MerchantModel::where(['id'=>$this->merchantID,'status'=>1])->count();
        if(!$count){
            $req['msg']='The current merchant is locked unable to operate the post';
            return $req;
        }
        if(isset($data['source']) && $data['source']){
            $sources=explode(',',$data['source']);
            $data['source']=json_encode($sources);
            //判断图片数量
            if($data['source_type']==1){
                if(count($sources)>9){
                    $req['msg']='The number of selected images cannot exceed 9';
                    return $req;
                }
            }
        }else{
            $data['source']=json_encode([]);
        }
        if(isset($data['source_type'])  && $data['source_type']==2){
            if(!isset($data['poster']) || empty($data['poster'])
            || !isset($data['duration']) || empty($data['duration'])){
                $req['msg']='You must add poster or duration';
                return $req;
            }
        }
        if(empty($data['start_time']) || empty($data['end_time'])){
            unset($data['start_time']);
            unset($data['end_time']);
        }
        $data['create_time']=date('Y-m-d H:i:s');
        $data['update_time']=date('Y-m-d H:i:s');
//        if(isset($data['start_time']) && isset($data['end_time'])){
//            //转换为标准时间
//            $data['start_time']=localToBase($data['start_time'],Session::get('country'));
//            $data['end_time']=localToBase($data['end_time'],Session::get('country'));
//        }

        PostsModel::insert($data);
        $req['code']=1;
        return $req;
    }

    public function edit($data){
        $req['code']=0;
        $merchant_id=$this->postsModel->getMerchant($data['id']);
        if(empty($merchant_id)){
            $req['msg']='The post does not exist';
            return $req;
        }
        if(Session::get('userType')!=config('data.role_type.merchant') || $merchant_id!=$this->merchantID){
            $req['msg']='Insufficient permissions for the current user';
            return $req;
        }

//        $data['label']=isset($data['label'])?json_encode(explode(',',$data['label'])):'[]';
        $files=request()->file('source');
        if(!empty($files)){
            foreach ($files as $file){
                $filename=$file->getInfo()['name'];
                $arr=explode('.',$filename);
                $suffix=array_pop($arr);
                //视频
                if(in_array($suffix,config('data.video_suffix'))){
                    if(count($files)>1){
                        $req['msg']='Allow only one video to be uploaded';
                        return $req;
                    }
                }
                //图片
                if(in_array($suffix,config('data.picture_suffix'))){
                    if(count($files)>9){
                        $req['msg']='Allow only one video to be uploaded';
                        return $req;
                    }
                }

                $info=$file->move('./uploads/posts');
                if($info){
                    $data['source'][]='uploads/posts/'.$info->getSaveName();
                }else{
                    $req['msg']=$file->getError();
                    return $req;
                }
            }

            if($data['source_type']==2){
                //获取视频时长与第一帧画面
                $pathInfo=pathinfo($data['source'][0]);
                $data['poster']=$pathInfo['dirname'].'/'.$pathInfo['filename'].'.jpg';
                getVideoCover($_SERVER['DOCUMENT_ROOT'].'/'.$data['source'][0],1,$_SERVER['DOCUMENT_ROOT'].'/'.$data['poster']);
                $data['duration']=getTime($_SERVER['DOCUMENT_ROOT'].'/'.$data['source'][0]);
            }
        }
//        if(isset($data['start_time']) && isset($data['end_time'])){
//            //转换为标准时间
//            $data['start_time']=localToBase($data['start_time'],Session::get('country'));
//            $data['end_time']=localToBase($data['end_time'],Session::get('country'));
//        }
        $data['update_time']=date('Y-m-d H:i:s');
        if(PostsModel::update($data,['id'=>$data['id']])){
            $req['code']=1;
            return $req;
        }else{
            $req['msg']='update error';
            return $req;
        }
    }

    public function delete($id){
        $merchant_id=$this->postsModel->getMerchant($id);
        if(Session::get('userType')!=config('data.role_type.merchant') || $merchant_id!=$this->merchantID){
            $req['msg']='Insufficient permissions for the current user';
            return $req;
        }
        $this->postsLikeModel->where('post_id',$id)->delete();
        $this->postsModel->where('id',$id)->delete();
    }

    public function like($id){
        $mid=$this->merchantID;
        $userType=Session::get('userType');
        $data=['type'=>$userType,'mid'=>$mid,'post_id'=>$id];
        $is_exists=PostLikeModel::where($data)->value('id');
        if($is_exists){
            //取消
            PostLikeModel::where('id',$is_exists)->delete();
            return -1;
        }else{
            $data['create_time']=date('Y-m-d H:i:s');
            //新增
            PostLikeModel::insert($data);
            return 1;
        }
    }

    public function lists($params){
        $where['p.status']=1;
        $where['merchant_id']=$params['id'];
        $data=$this->postsModel->getPosts($where,$params);
        if($data['total']>0){
            $timeZone=$timeZone=$this->airportModel->getTimeZone($params['airport_id']);
            $data['result']=self::handleData($data['result'],$this->merchantID,$timeZone);
        }

        return $data;
    }

    public function myLike($params){
        $params['user_type']=Session::get('userType');
        $data=$this->postsModel->myLike($params);
        if($data['total']>0){
            if(isset($params['airport_id'])){
                $timeZone=$this->airportModel->getTimeZone($params['airport_id']);
            }else{
                $timeZone=AreaModel::where('id',$params['country'])->value('timezone');
            }
            $data['result']=self::handleData($data['result'],$this->merchantID,$timeZone);
        }
        return $data;
    }

    public static function handleData($data,$uid,$timeZone){
        foreach ($data as $key=>$val){
//            if(isset($val['avatar'])){
//                $data[$key]['avatar']=getMerchantAvatar($val['avatar']);
//            }
            if(array_key_exists('avatar',$val)) {
                $data[$key]['avatar']=getMerchantAvatar($val['avatar']);
            }
            $list=[];
            if($val['source']){
                $sources=json_decode($val['source'],true);
                foreach ($sources as $source){
                    $list[]=get_file_path($source);
                }
                if($val['source_type']==2){
                    $data[$key]['poster']=get_file_path($val['poster']);
                }
            }

            $data[$key]['source']=$list;
            if($data[$key]['start_time']){
                $data[$key]['event_time']=handleEventTime($data[$key]['start_time'],$data[$key]['end_time']);
            }else{
                $data[$key]['event_time']='';

            }
            if(isset($val['airport'])){
                $data[$key]['airport']=AirportModel::where('id',$val['airport'])->value('name');
            }
            $data[$key]['like_count']=PostLikeModel::where('post_id',$val['id'])->count();
            $data[$key]['is_like']=0;
            if($uid){
                $data[$key]['is_like']=PostLikeModel::where(['post_id'=>$val['id'],'type'=>Session::get('userType'),'mid'=>$uid])->count();
            }
            $data[$key]['format_create_time']=date('Y-m-d',strtotime($val['create_time']));
            $data[$key]['create_time']=openTime($val['create_time'],$timeZone);
            if($val['label']){
                $data[$key]['label']=LabelModel::where('id',$val['label'])->field('name,color')->find()->toArray();
            }else{
                $data[$key]['label']=null;
            }
        }

        return $data;
    }

}